package com.tools.untils;

import com.common.LO.FiscoLO;
import com.common.LO.Fisco_accountLO;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.CryptoSuite;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Slf4j
public class Create_ {
    // 获取配置文件路径
    public static final String configFile = Create_.class.getClassLoader().getResource("config-example.toml").getPath();
    public static String create_hash256(String input)  {
            // 获取MessageDigest的实例，使用SHA-256算法
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        // 对字符串进行编码
            byte[] encodedhash = digest.digest(input.getBytes(java.nio.charset.StandardCharsets.UTF_8));
            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : encodedhash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
        return hexString.toString();
    }
    public static Fisco_accountLO create_fisco_account(){
        // 初始化BcosSDK
        BcosSDK sdk = BcosSDK.build(configFile);
        // 为群组1初始化client
        Client client = sdk.getClient(Integer.valueOf(1));
        // 非国密类型的CryptoSuite
        CryptoSuite cryptoSuite = client.getCryptoSuite();
        // 创建国密类型的CryptoSuite
        // 随机生成非国密公私钥对
        CryptoKeyPair cryptoKeyPair = cryptoSuite.createKeyPair();
        // 获取账户地址
        return Fisco_accountLO.builder()
                .accountAddress(cryptoKeyPair.getAddress())
                .hexPrivateKey(cryptoKeyPair.getHexPrivateKey())
                .build();
    }
    public static FiscoLO create_fisco_sdk(String hexPrivateKey){
        // 初始化BcosSDK
        BcosSDK sdk = BcosSDK.build(configFile);
        // 为群组1初始化client
        Client client = sdk.getClient(Integer.valueOf(1));
        // 非国密类型的CryptoSuite
        CryptoSuite cryptoSuite = client.getCryptoSuite();
        CryptoKeyPair keyPair = cryptoSuite.getCryptoKeyPair().createKeyPair(hexPrivateKey);
        return  FiscoLO.builder()
                .client(client)
                .cryptoKeyPair(keyPair)
                .build();
    }

}
